<?php

namespace App\Repositories\Goods;

use Illuminate\Support\Facades\Cache;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Models\Goods\GoodsWid;

/**
 * Class GoodsWidRepositoryEloquent.
 *
 * @package namespace App\Repositories\Goods;
 */
class GoodsWidRepositoryEloquent extends BaseRepository implements GoodsWidRepository
{
    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return GoodsWid::class;
    }

    

    /**
     * Boot up the repository, pushing criteria
     */
    public function boot()
    {
        $this->pushCriteria(app(RequestCriteria::class));
    }

    /**
     * 获取指定商品id详情
     * @author Jerry
     * @param int $goodsId
     * @param int $wid
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    public function findGoodsWidInfoByGoodsId(int $goodsId, int $wid = 8)
    {
        $where = [
            'g.goods_id'    =>  $goodsId,
            'g.is_delete'   =>  0,
            'gw.is_on_sale' =>  1,
            ['g.original_img', '<>', "''"],
            ['g.goods_img', '<>', "''"],
        ];

        $field = [
            'gw.goods_id',
            'g.goods_name',
            'g.goods_thumb',
            'g.goods_img',
            'g.goods_brief',
            'g.is_presell',
            'g.promote_price',
            'g.promote_start_date',
            'g.promote_end_date',
            'g.goods_number',
            'g.warn_number',
            'g.original_img',
            'g.is_on_sale',
            'g.promote_goods_number',
            'g.promote_today_number',
            'g.is_buynow',
            'g.spec_unit',
            'g.spec_value',
            'g.min_buy_num',
            'g.delivery_type',
            'g.delivery_cycle',
            'gs.practical_num',
            'g.promote_user_rank',
            'g.is_promote',
        ];

        return Cache::rememberForever("goodsInfo:{$goodsId},{$wid}", function () use ($field, $where, $wid) {
            return \DB::table('goods_wid_' . $wid . ' as gw')
                ->leftJoin('goods as g', 'gw.goods_id', '=', 'g.goods_id')
                ->leftJoin('goods_storage as gs', function ($join) use ($wid) {
                    $join->on('g.goods_id', '=', 'gs.goods_id')->where('gs.wid', '=', $wid);
                })
                ->where($where)
                ->get($field)
                ->first();
        });

    }
    
}
